package com.picture.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.picture.constant.MessageConstant;
import com.picture.context.BaseContext;
import com.picture.mapper.PictureMapper;
import com.picture.mapper.PictureTagMapper;
import com.picture.mapper.TagTypeMapper;
import com.picture.mapper.UserMapper;
import com.picture.pojo.dto.PictureDto;
import com.picture.pojo.dto.PictureTagDto;
import com.picture.pojo.entity.Picture;
import com.picture.pojo.entity.PictureTag;
import com.picture.pojo.entity.TagType;
import com.picture.pojo.entity.User;
import com.picture.result.Result;
import com.picture.service.PictureTagService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
public class PictureTagServiceImpl implements PictureTagService {

    // 注入TagTypeMapper的接口对象
    @Resource
    private TagTypeMapper tagtypeMapper;

    // 注入PictureTagMapper的接口对象
    @Resource
    private PictureTagMapper pictureTagMapper;

    // 注入PictureMapper的接口对象
    @Resource
    private PictureMapper pictureMapper;

    // 注入UserMapper的接口对象
    @Resource
    private UserMapper userMapper;

    /**
     * 插入标记坐标和类型信息
     * @param pictureDto 图片坐标信息
     * @return 返回响应结果
     */
    @Override
    // 开启事务控制，如果发生异常，则数据回滚
    @Transactional
    public Result<String> insert(PictureDto pictureDto) {
        // 判断是否请求是否被接收
        if(pictureDto == null) {
            throw new RuntimeException(MessageConstant.REQUEST_PARAMETER_EMPTY);
        }
        // 判断请求中的标记和类型信息是否存在
        //if (pictureDto.getPictureTagDtoList() == null) {
        //     throw new RuntimeException(MessageConstant.PICTURE_TAG_EMPTY);
        // }

        // 修改图片的操作人id和描述信息
        // 创建LambdaQueryWrapper条件对象
        LambdaQueryWrapper<Picture> pictureQueryWrapper = new LambdaQueryWrapper<>();
        // 设置图片Id条件
        pictureQueryWrapper.eq(Picture::getPictureId, pictureDto.getPictureId());
        Picture picture = pictureMapper.selectOne(pictureQueryWrapper);
        // 获取操作人id
        Long userId = BaseContext.getCurrentId();
        // 获取当前用户的所有信息
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getId, userId);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        String username = user.getName();
        // 获取管理员的userId
        LambdaQueryWrapper<User> rootLambdaQueryWrapper = new LambdaQueryWrapper<>();
        rootLambdaQueryWrapper.eq(User::getName, "root");
        User root = userMapper.selectOne(rootLambdaQueryWrapper);
        Integer rootId = root.getId();
        // 判断用户是否有权限操作
        if(picture.getUserId() == null || userId.equals(picture.getUserId().longValue()) || username.equals("root")) {
            Picture newPicture = new Picture();
            // 设置当前图片的id
            newPicture.setPictureId(picture.getPictureId());
            // 设置当前图片的类型id
            newPicture.setPictureCategoryId(pictureDto.getPictureCategoryId());
            // 设置当前图片的描述信息
            newPicture.setDescription(pictureDto.getDescription().trim());

            //设置图片班级
            newPicture.setAclass(pictureDto.getAclass());
            // 设置当前图片的更新时间
            newPicture.setUpdateTime(LocalDateTime.now());
            // 如果管理员对该图片进行了操作，则设置图片状态为已被管理员确认
            if(username.equals("root")) {
                newPicture.setPictureStatus("2");
                newPicture.setUserId(Math.toIntExact(userId));
                // 如果当前图片未被用户操作并且标记信息不为空，则设置当前图片的用户权限
           } else /*if(picture.getUserId() == null && pictureDto.getPictureTagDtoList().size() == 0)*/ {
                // 设置当前图片已经被操作
                newPicture.setPictureStatus("1");
                newPicture.setUserId(Math.toIntExact(userId));
            }
            pictureMapper.updateById(newPicture);
        } else if(picture.getUserId().equals(rootId)) {
            // 如果当前图片为管理员已经确认的图片，则返回图片已经被管理员确认
            throw new RuntimeException(MessageConstant.ROOT_CONFIRM);
        } else {
            // 返回当前用户没有权限
            throw new RuntimeException(MessageConstant.NOT_AUTHORITY);
        }

        // 如果标记信息和标记类型不为空
        if(pictureDto.getPictureTagDtoList().size() != 0) {
            // 创建LambdaQueryWrapper条件对象
            LambdaQueryWrapper<PictureTag> pictureTagQueryWrapper = new LambdaQueryWrapper<>();
            // 设置图片Id条件
            pictureTagQueryWrapper.eq(PictureTag::getPictureId, pictureDto.getPictureId());
            // 删除图片中原有的坐标信息
            pictureTagMapper.delete(pictureTagQueryWrapper);

            // 循环遍历图片标记信息
            for ( PictureTagDto pictureTagDto: pictureDto.getPictureTagDtoList()) {
                // 获取标记类型id
                Long typeId = pictureTagDto.getTypeId();
                // 查找数据
                TagType tagType = tagtypeMapper.selectById(typeId);
                // 判断标记类型是否存在
                if(tagType == null) {
                    throw new RuntimeException(MessageConstant.TAG_TYPE_NOT_EXIST);
                }

                // 构造PictureTag对象
                PictureTag pictureTag = new PictureTag(
                        pictureDto.getPictureId(),
                        typeId,
                        pictureTagDto.getX1(),
                        pictureTagDto.getY1(),
                        pictureTagDto.getX2(),
                        pictureTagDto.getY2(),
                        pictureTagDto.getColor()
                );
                // 保存坐标信息等
                pictureTagMapper.insert(pictureTag);
            }
        }

        // 返回响应结果
        return Result.success(MessageConstant.SAVE_SUCCESS);
    }
}
